/*
 * stringutil.cpp
 *
 *  Created on: Jun 25, 2012
 *      Author: burek
 */

#include "stringutil.h"
#include <cstring>

char * trimSpaces(char * text)
{
	int l = strlen(text);
	for(int i = l - 1; i >= 0; --i)
	{
		if(text[i] == ' ')
			l--;
		else
			break;
	}

	text[l] = '\0';
	int shift = 0;

	for(int i = 0; i < l; ++i)
	{
		if(text[i] != ' ')
			break;
		else
			shift = i + 1;
	}

	if(shift > 0)
	{
		for(int i = 0; i < l; ++i)
			text[i] = text[i + shift];
	}

	l -= shift;
	text[l] = '\0';

	return text;
}

char * trimNL(char * text)
{
	int len = strlen(text);
	for(int i = len - 1; i >= 0; --i)
	{
		if(text[i] == '\n')
			text[i] = '\0';
		else if(text[i] == '\r')
			text[i] = '\0';
		else if(text[i] == '\f')
			text[i] = '\0';
		else
			break;
	}
	return text;
}

bool startsWith(const char * text, const char * prefix)
{
	if(text == NULL || prefix == NULL)
		return false;
	int tlen = strlen(text);
	int plen = strlen(prefix);
	if(plen > tlen)
		return false;
	return strncmp(text, prefix, plen) == 0;
}

bool endsWith(const char * text, const char * suffix)
{
	int len1 = strlen(text);
	int len2 = strlen(suffix);
	if(len2 > len1) return false;
	if(len1 == 0 || len2 == 0) return false;

	return strcmp(text + len1 - len2, suffix) == 0;
}

char * chrReplace(char * text, char from, char to)
{
	while(*text)
	{
		if(*text == from)
			*text = to;
		text++;
	}
	return text;
}
